package com.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;

public class ContextUtil {
	private static ApplicationContext applicationContext;
	public static void setApplicationContext(ApplicationContext applicationContext) {
		synchronized (ContextUtil.class) {
			ContextUtil.applicationContext = applicationContext;
			ContextUtil.class.notifyAll();
		}
	}

	public static ApplicationContext getApplicationContext() {
		synchronized (ContextUtil.class) {
			while (applicationContext == null) {
				try {
					System.out.println("1111111111");
					ContextUtil.class.wait(6000);
				} catch (InterruptedException ex) {
				}
			}
			return applicationContext;
		}
		//return applicationContext;
	}

	/**
	 * 获取bean
	 *
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		try {
			return getApplicationContext().getBean(name);
		} catch (Exception e) {
			return null;
		}

	}

	/**
	 * 获取bean
	 *
	 * @param cls
	 * @return
	 */
	public static <T> T getBean(Class<T> cls) {
		return getApplicationContext().getBean(cls);
	}


	/**
	 * 触发事件
	 *
	 * @param event
	 */
	public static void publishEvent(ApplicationEvent event) {
		getApplicationContext().publishEvent(event);
	}

}
